package controllers;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Dao.DBConnect;
import application.Main;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import models.CarProductModel;
import models.OrderModel;
import models.ShopModel;


public class SalesController implements Initializable {

    static int userid;
    static String uname;


    @FXML
    private Button btn_p_add;
    @FXML
    private Button btn_p_edit;

//    @FXML
//    private Button btn_p_del;



    @FXML
    private Button btnEdit;
    @FXML
    private Label innerlb01;
    @FXML
    private Label innerlb02;
    @FXML
    private TextField innertxt;
    @FXML
    private VBox innervbox01;


    CarProductModel cpm;
    OrderModel od;

    /***** TABLEVIEW Product *********************************************************************/


    @FXML
    private HBox hb01;
    @FXML
    private Button btnDel;
    @FXML
    private HBox hb02;
    @FXML
    private TableView<CarProductModel> tblProduct2;
    @FXML
    private TableColumn<CarProductModel, String> product_name;
    @FXML
    private TableColumn<CarProductModel, Long> product_price;
    @FXML
    private TableColumn<CarProductModel, Integer> pid;
    @FXML
    private TableColumn<CarProductModel, Integer> product_sid;
    @FXML
    private Label lb_p_01;
    @FXML
    private TextField txt_p_01;
    @FXML
    private TextField txt_p_02;
    @FXML
    private  ChoiceBox cb_p_01;

    @FXML
    private VBox vbox_m_p;



//    ---------------------------------------------------------

    @FXML
    private TableView<OrderModel> order_view01;
    @FXML
    private TableColumn<OrderModel, Integer> oid;
    @FXML
    private TableColumn<OrderModel, String> product_name_o;
    @FXML
    private TableColumn<OrderModel, String> order_status;
    @FXML
    private TableColumn<OrderModel, Integer> pur_num;


    @FXML
    private TableView<OrderModel> order_view02;
    @FXML
    private TableColumn<OrderModel, Integer> oid2;
    @FXML
    private TableColumn<OrderModel, String> product_name_o2;
    @FXML
    private TableColumn<OrderModel, String> order_status2;
    @FXML
    private TableColumn<OrderModel, Integer> pur_num2;

    @FXML
    private Label lbinfo;

    ShopModel sp;

    ButtonType foo = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE);
    ButtonType bar = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
    Alert a = new Alert(Alert.AlertType.NONE,"",foo,bar);
    Alert b = new Alert(Alert.AlertType.CONFIRMATION,"",foo);


    public void initialize(URL location, ResourceBundle resources) {

        pid.setCellValueFactory(new PropertyValueFactory<CarProductModel, Integer>("proId"));
        product_name.setCellValueFactory(new PropertyValueFactory<CarProductModel, String>("proName"));
        product_price.setCellValueFactory(new PropertyValueFactory<CarProductModel, Long>("proPrice"));
        product_sid.setCellValueFactory(new PropertyValueFactory<CarProductModel, Integer>("proSid"));
        pid.setStyle( "-fx-alignment: CENTER;");
        product_name.setStyle( "-fx-alignment: CENTER;");
        product_price.setStyle( "-fx-alignment: CENTER;");
        product_sid.setStyle( "-fx-alignment: CENTER;");
        tblProduct2.setVisible(Boolean.FALSE);
        // auto adjust width of columns depending on their content

        tblProduct2.setColumnResizePolicy((param) -> true);
        Platform.runLater(() -> customResize(tblProduct2));
        oid.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("id"));
        product_name_o.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("product_name"));
        order_status.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("order_status"));
        pur_num.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("p_num"));
        order_view01.setVisible(Boolean.FALSE);
        oid.setStyle( "-fx-alignment: CENTER;");
        product_name_o.setStyle( "-fx-alignment: CENTER;");
        order_status.setStyle( "-fx-alignment: CENTER;");
        pur_num.setStyle( "-fx-alignment: CENTER;");
//		hb01.setVisible(Boolean.FALSE);
//		hb02.setVisible(Boolean.FALSE);
        innervbox01.setVisible(Boolean.FALSE);

        oid2.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("id"));
        product_name_o2.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("product_name"));
        order_status2.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("order_status"));
        pur_num2.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("p_num"));
        order_view02.setVisible(Boolean.FALSE);
        oid2.setStyle( "-fx-alignment: CENTER;");
        product_name_o2.setStyle( "-fx-alignment: CENTER;");
        order_status2.setStyle( "-fx-alignment: CENTER;");
        pur_num2.setStyle( "-fx-alignment: CENTER;");
        btn_p_add.setDisable(true);
        btn_p_edit.setDisable(true);


//   init cb list
        List<ShopModel> sps = new ArrayList<>();
        List<String> ls = new ArrayList<>();
        sp = new ShopModel();
        sps = sp.getAll();
        System.out.println(sps.toString());
        for (ShopModel str : sps) {

            ls.add(String.valueOf(str.getSid()));

        }
        System.out.println(ls.toString());
        cb_p_01.getItems().addAll(ls);
//        cb_p_01.setValue("1");






    }

    public void customResize(TableView<?> view) {

        AtomicLong width = new AtomicLong();
        view.getColumns().forEach(col -> {
            width.addAndGet((long) col.getWidth());
        });
        double tableWidth = view.getWidth();

        if (tableWidth > width.get()) {
            view.getColumns().forEach(col -> {
                col.setPrefWidth(col.getWidth()+((tableWidth-width.get())/view.getColumns().size()));
            });
        }
    }

    public void viewProduct() throws IOException {

        vbox_m_p.setVisible(Boolean.TRUE);
        order_view01.setVisible(Boolean.FALSE);
        order_view02.setVisible(Boolean.FALSE);
        lb_p_01.setText("");
        txt_p_01.setText("");
        txt_p_02.setText("");
        cb_p_01.setValue("1");
//		hb01.setVisible(Boolean.FALSE);
//		hb02.setVisible(Boolean.FALSE);
        innervbox01.setVisible(Boolean.FALSE);
        tblProduct2.setVisible(Boolean.TRUE);
        tblProduct2.getItems().setAll(cpm.getAllProduct());
        lbinfo.setText("Welcome " + uname + " now you are viewing the product");
        btn_p_add.setDisable(false);


    }

    /***** End TABLEVIEW intel *********************************************************************/

    public void logout() {
        // System.exit(0);
        try {
            AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/views/LoginView.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("/application/styles.css").toExternalForm());
            Main.stage.setScene(scene);
            Main.stage.setTitle("Login");

        } catch (Exception e) {
            System.out.println("Error occured while inflating view: " + e);
        }
    }



    public static void setUserid(int user_id) {
        userid = user_id;
        System.out.println("Welcome id " + userid);
    }
    public static void setUname(String user_name) {
        uname = user_name;
        System.out.println("Welcome id " + uname);

    }


    public SalesController() {


        cpm = new CarProductModel();
        od = new OrderModel();

    }

    public void purchaseOrder(MouseEvent mouseEvent) {

        System.out.println("mouse click");
        TablePosition tablePosition=tblProduct2.getSelectionModel().getSelectedCells().get(0);
        int row=tablePosition.getRow();
        CarProductModel item=tblProduct2.getItems().get(row);
        TableColumn tableColumn=tablePosition.getTableColumn();
        String data= (String) tableColumn.getCellObservableValue(item).getValue();
        System.out.println(data);
        System.out.println(userid);
        CarProductModel cpms1 = tblProduct2.getSelectionModel().getSelectedItem();
        System.out.println(cpms1.toString());

        TextInputDialog dialog = new TextInputDialog("Enter quantity to create order");
        dialog.setTitle("U&E Car Dealer Shop Portal");
        dialog.setHeaderText("Create Transaction");
        dialog.setContentText("Please enter the purchase quantity:");
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            System.out.println("Enter entry is : " + result.get());
//            cm.insertRecord(userid,Double.parseDouble(result.get()));
//            cpm.insertRecord(userid, Integer.parseInt(result.get()),cpms1.getProId());
            System.out.println(cpms1.toString() );
        }

    }

    public void viewOrders(ActionEvent actionEvent) {
        vbox_m_p.setVisible(Boolean.FALSE);
        tblProduct2.setVisible(Boolean.FALSE);
        order_view01.setVisible(Boolean.TRUE);
        order_view02.setVisible(Boolean.FALSE);
        btnEdit.setDisable(true);
        btnDel.setDisable(true);
//		hb01.setVisible(Boolean.TRUE);
//		hb02.setVisible(Boolean.TRUE);
        innervbox01.setVisible(Boolean.TRUE);
        order_view01.getItems().setAll(od.s_getAllOrders());
        lbinfo.setText("Welcome " + uname + " now you are viewing all your orders");
    }



    public void deleteorder(MouseEvent mouseEvent) {

        a.setAlertType(Alert.AlertType.CONFIRMATION);
        a.setContentText("Do you want to cancel the order??");
        a.setHeaderText("");

        Optional<ButtonType> result = a.showAndWait();

        if (result.get() == foo) {
            ObservableList<OrderModel> selectedRows, allOrder;
            allOrder = order_view01.getItems();

            //this gives us the rows that were selected
            selectedRows = order_view01.getSelectionModel().getSelectedItems();

            //loop over the selected rows and remove the Person objects from the table
            for (OrderModel order: selectedRows)
            {
                allOrder.remove(order);
                System.out.println(order.getId());
                od.s_deleteRecord(order.getId());
                b.setContentText("Order canceled !!!");
                b.setHeaderText("");
                b.showAndWait();
            }
            btnEdit.setDisable(true);
            btnDel.setDisable(true);
        }

    }

    public static boolean isValid(String s)
    {

        Pattern p = Pattern.compile("[0-9]+");

        Matcher m = p.matcher(s);
        return (m.find() && m.group().equals(s));
    }

    public void orderUpdate(MouseEvent mouseEvent) {

        a.setAlertType(Alert.AlertType.CONFIRMATION);
        a.setContentText("Do you want to update the record??");
        a.setHeaderText("");

        Optional<ButtonType> result = a.showAndWait();

        if (result.get() == foo) {
            ObservableList<OrderModel> selectedRows, allOrder;
            allOrder = order_view01.getItems();

            //this gives us the rows that were selected
            selectedRows = order_view01.getSelectionModel().getSelectedItems();

            //loop over the selected rows and remove the Person objects from the table
            for (OrderModel order: selectedRows)
            {
//				allOrder.remove(order);
                System.out.println(order.getId());

                od.s_editRecord(order.getId());
                b.setContentText("Car delivered  !!!");
                b.setHeaderText("");
                b.showAndWait();


                order_view01.getItems().setAll(od.s_getAllOrders());

            }

            btnEdit.setDisable(true);
            btnDel.setDisable(true);

        }

    }






    public void editOrder(MouseEvent mouseEvent) {
        ObservableList<OrderModel> selectedRows, allOrder;
        allOrder = order_view01.getItems();

        //this gives us the rows that were selected
        selectedRows = order_view01.getSelectionModel().getSelectedItems();

        //loop over the selected rows and remove the Person objects from the table
        for (OrderModel order: selectedRows)
        {
            innerlb01.setText(order.getProduct_name());
            innerlb02.setText(order.getOrder_status());
            innertxt.setText(String.valueOf(order.getP_num()));
        }
        btnEdit.setDisable(false);
        btnDel.setDisable(false);
    }

    public void viewHisOrders(ActionEvent actionEvent) {

        vbox_m_p.setVisible(Boolean.FALSE);
        tblProduct2.setVisible(Boolean.FALSE);
        order_view01.setVisible(Boolean.FALSE);
        order_view02.setVisible(Boolean.TRUE);

        order_view02.getItems().setAll(od.s_getHisOrders());
        lbinfo.setText("Welcome " + uname + " now you are viewing all your orders");
    }

    public void insertProduct(MouseEvent mouseEvent) {

        System.out.println(txt_p_01.getText() + "  " +txt_p_02.getText());
//        CarProductModel cpm1 = new CarProductModel();
        a.setAlertType(Alert.AlertType.CONFIRMATION);
        a.setContentText("Do you want to add new Product??");
        a.setHeaderText("");

        Optional<ButtonType> result = a.showAndWait();

        if (result.get() == foo) {
            if (isValid(txt_p_02.getText())) {
                cpm.setProName(txt_p_01.getText());
                cpm.setProPrice(Long.parseLong(txt_p_02.getText()));
                cpm.setProSid(Integer.parseInt(cb_p_01.getValue().toString()));
                cpm.insertProduct(cpm);
                //			cpm.insertRecord(userid, Integer.parseInt(result.get()),cpms1.getProId());
                System.out.println(cpm.toString());
                tblProduct2.getItems().setAll(cpm.getAllProduct());
                b.setContentText("New Car added !!!");
                b.setHeaderText("");
                b.showAndWait();

            } else {

                b.setContentText("Price must input number !!!");
                b.setHeaderText("");
                b.showAndWait();
            }
        }

    }



    public void oprProduct(MouseEvent mouseEvent) {

        System.out.println("mouse click");
        btn_p_add.setDisable(true);
        btn_p_edit.setDisable(false);


        CarProductModel cpms1 = tblProduct2.getSelectionModel().getSelectedItem();
        System.out.println(cpms1.toString());
        lb_p_01.setText(String.valueOf(cpms1.getProId()));
        txt_p_01.setText(cpms1.getProName());
        txt_p_02.setText(String.valueOf(cpms1.getProPrice()));
        cb_p_01.setValue(String.valueOf(cpms1.getProSid()));

    }

    public void editProduct(MouseEvent mouseEvent) {
        System.out.println(txt_p_01.getText() + "  " +txt_p_02.getText());
        CarProductModel cpms1 = tblProduct2.getSelectionModel().getSelectedItem();
        System.out.println(cpms1.toString());
        System.out.println(txt_p_01.getText());
        a.setAlertType(Alert.AlertType.CONFIRMATION);
        a.setContentText("Do you want to edit the Product??");
        a.setHeaderText("");

        Optional<ButtonType> result = a.showAndWait();

        if (result.get() == foo) {
            if (isValid(txt_p_02.getText())) {
                cpm.setProId(Integer.parseInt(lb_p_01.getText()));
                cpm.setProName(txt_p_01.getText());
                cpm.setProPrice(Long.parseLong(txt_p_02.getText()));
                cpm.setProSid(Integer.parseInt(cb_p_01.getValue().toString()));
                System.out.println(" in editproduct fund " + cpm.getProSid() + cb_p_01.getValue().toString());
                cpm.updateProduct(cpm);
                //			cpm.insertRecord(userid, Integer.parseInt(result.get()),cpms1.getProId());
                //        System.out.println(cpm.toString() );
                tblProduct2.getItems().setAll(cpm.getAllProduct());
                btn_p_edit.setDisable(true);
                b.setContentText("Car edited !!!");
                b.setHeaderText("");
                b.showAndWait();
            } else {

                b.setContentText("Price must input number !!!");
                b.setHeaderText("");
                b.showAndWait();
            }
        }
    }
}
